'use strict';

const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const awaitWriteStream = require('await-stream-ready').write;

class FileController extends Controller {

  /**
   *
   * @description 上传文件
   *
   * @memberof FileController
   */
  async upload() {

    const { ctx } = this;
    let fileStream = null;
    try {
      fileStream = await ctx.getFileStream();
    } catch (e) {
      ctx.body = '出错:[文件格式不支持，请管理员添加相应的文件类型]' + e.message;
      return;
    }
    const fileName = Math.random() + fileStream.filename;
    const filepath = this.config.baseDir + '/' + fileName;
    const subdir = typeof ctx.query.subdir === 'undefined' ? '' : '/' + ctx.query.subdir;

    // 存储文件
    const writeStream = fs.createWriteStream(filepath);
    await awaitWriteStream(fileStream.pipe(writeStream));

    // 获取hash
    const data = await fs.readFileSync(filepath);
    const fsHash = crypto.createHash('sha256');
    await fsHash.update(data);
    const hash = await fsHash.digest('hex');

    // 复制图片
    const extname = path.extname(fileName);
    const newFile = hash + extname;
    const dir = this.config.uploadDir + subdir;
    const uniFile = dir + '/' + newFile;

    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
    }
    await fs.writeFileSync(uniFile, data);

    // 删除旧文件
    fs.unlinkSync(filepath);

    // 存储索引
    const id = await ctx.service.file.save(hash, extname);
    ctx.body = this.config.webHost + subdir + '/' + newFile + '?id=' + id;
  }


  async delete() {
    const { ctx } = this;
    const url = ctx.query.file;
    const urlInfo = new URL(url);
    const params = new URLSearchParams(urlInfo.search);
    const id = params.get('id');
    const file = urlInfo.pathname.replace('/public/uploads/','');
    const res = await ctx.service.file.delete(id,file);
    ctx.body = res ? "success" : "fail";
  }

  async submit() {
    const { ctx } = this;
    let file = ctx.query.file;
    const fileInfo = new URL(file);
    const params = new URLSearchParams(fileInfo.search);
    const fileId = params.get('id');
    await ctx.service.file.submit(fileId);
    ctx.body = "success";
  }
}

module.exports = FileController;
